package dao

import (
	"context"
	"errors"
	"sale-admin/internal/dal"
	"sale-admin/internal/models"
	"time"

	"192.168.1.75/go-pkg/helper"
)

type DataCompareTemplate struct{}

func (DataCompareTemplate) Create(ctx context.Context, query *dal.Query, merchantID, UID, name, content string) (err error) {
	m := query.DataCompareTemplate
	var d models.DataCompareTemplate
	d.ID, _ = helper.UUID{}.String()
	d.MerchantID = merchantID
	d.UserID = UID
	d.Name = name
	d.Content = content
	d.CreatedAt = time.Now().Unix()
	m.WithContext(ctx).Create(&d)
	return
}

func (DataCompareTemplate) Update(ctx context.Context, query *dal.Query, ID, merchantID, UID, name, content string) (err error) {
	m := query.DataCompareTemplate
	res, _ := m.WithContext(ctx).
		Where(m.ID.Eq(ID)).
		Where(m.MerchantID.Eq(merchantID)).
		Where(m.UserID.Eq(ID)).
		Where(m.DeletedAt.Eq(0)).
		UpdateColumnSimple(m.Name.Value(name), m.Content.Value(content))
	if res.RowsAffected < 0 {
		return errors.New("编辑失败")
	}
	return
}

func (DataCompareTemplate) List(ctx context.Context, query *dal.Query, merchantID, UID string) (data []*models.DataCompareTemplate, count int64, err error) {
	m := query.DataCompareTemplate
	tx := m.WithContext(ctx).
		Where(m.DeletedAt.Eq(0))
	if merchantID != "" {
		tx = tx.Where(m.MerchantID.Eq(merchantID))
	}
	if UID != "" {
		tx = tx.Where(m.UserID.Eq(UID))
	}
	data, _ = tx.Find()
	count, err = tx.Count()
	return
}

func (DataCompareTemplate) Detail(ctx context.Context, query *dal.Query, ID, merchantID, UID string) (res *models.DataCompareTemplate, err error) {
	m := query.DataCompareTemplate
	tx := m.WithContext(ctx).
		Where(m.DeletedAt.Eq(0)).
		Where(m.ID.Eq(ID))

	if merchantID != "" {
		tx = tx.Where(m.MerchantID.Eq(merchantID))
	}
	if UID != "" {
		tx = tx.Where(m.UserID.Eq(UID))
	}
	res, err = tx.Take()
	return
}

func (DataCompareTemplate) Delete(ctx context.Context, query *dal.Query, ID, merchantID, UID string) (err error) {
	m := query.DataCompareTemplate
	res, _ := m.WithContext(ctx).
		Where(m.ID.Eq(ID)).
		Where(m.MerchantID.Eq(merchantID)).
		Where(m.UserID.Eq(UID)).
		Where(m.DeletedAt.Eq(0)).
		Update(m.DeletedAt, time.Now().Unix())
	if res.RowsAffected != 1 || res.Error != nil {
		err = errors.New("删除失败")
	}
	return
}
